package cn.demoa.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDelListener {
    private ListView StuListView;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private ArrayList<Student> searchResultList = new ArrayList<>();
    private StuAdapter adapter;
    private Button btnAddStu;
    private Button btnSearch;
    private EditText editKeyword;
    private boolean isResultList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("学生列表");

        initStuList();

        initAdapter();

        initListView();

        initBtnAddStu();

        initSearchView();
    }

    /*初始化搜索模块*/
    private void initSearchView() {
        editKeyword = findViewById(R.id.edit_keyword);
        btnSearch = findViewById(R.id.btn_search);

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword = editKeyword.getText().toString().trim();
                //使用学生列表和关键字，取得结果
                search(studentArrayList,keyword);
                adapter.changeData(searchResultList);
                isResultList = true;
            }
        });

        editKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = editKeyword.getText().toString().trim();
                search(studentArrayList,keyword);
                adapter.changeData(searchResultList);
                isResultList = true;
            }
        });
    }

    /*使用学生列表和关键字，取得搜索结果*/
    private void search(ArrayList<Student> studentArrayList, String keyword) {
        searchResultList.clear();
        for (int i=0;i<studentArrayList.size();i++){
            Student s = studentArrayList.get(i);
            if (s.getName().contains(keyword)){
                searchResultList.add(s);
            }
            //年龄搜索
            else if (String.valueOf(s.getAge()).equals(keyword)){
                searchResultList.add(s);
            }
        }
    }

    /*设置添加学生按钮*/
    private void initBtnAddStu() {
        btnAddStu = findViewById(R.id.btn_addStu);

        btnAddStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddStuActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
    }

    /*初始化ListView*/
    private void initListView() {
        StuListView = findViewById(R.id.name_listview);
        StuListView.setAdapter(adapter);

        //鼠标点击item显示学生信息
        StuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Student s = studentArrayList.get(i);
                if (isResultList){
                    s = searchResultList.get(i);
                }
                Toast.makeText(MainActivity.this, "姓名:" + s.getName() + " 年龄:"
                        + s.getAge(), Toast.LENGTH_SHORT).show();

                Intent intent = new Intent();
                intent.setClass(MainActivity.this, EditStuActivity.class);
                intent.putExtra("NAME", s.getName());
                intent.putExtra("AGE", s.getAge());
                intent.putExtra("IMGID", s.getImgid());
                intent.putExtra("NO", s.getNo());
                startActivityForResult(intent, 1002);
            }
        });
    }

    /*初始化适配器*/
    private void initAdapter() {
        adapter = new StuAdapter(MainActivity.this, studentArrayList, MainActivity.this);
    }

    /*返回修改的数据结果*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.e("MainActivity", " requestCode = " + requestCode + " resultCode = " + resultCode);

        if (data == null) {
            return;
        }

        if (resultCode == 2001) {
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);
            int imgId = data.getIntExtra("IMG", R.drawable.dog1);

            Student s = new Student("18001",imgId, name, age);
            studentArrayList.add(s);
            adapter.notifyDataSetChanged();
        } else if (resultCode == 3001) {
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);
            int imgId = data.getIntExtra("IMG", R.drawable.dog1);
            String no = data.getStringExtra("NO");

            for(int i=0; i<studentArrayList.size(); i++){
                Student s = studentArrayList.get(i);

                if(s.getNo().equals(no)) {
                    s.setName(name);
                    s.setAge(age);
                    s.setImgid(imgId);
                }
            }
            String keyword = editKeyword.getText().toString().trim();
            // 使用学生列表和关键字 得到搜索结果列表
            search(studentArrayList, keyword);
            adapter.changeData(searchResultList);
            isResultList = true;
        }
    }

    /*初始化学生数据*/
    private void initStuList() {
        Student s1 = new Student("18001",R.drawable.dog1, "张三", 18);
        Student s2 = new Student("18002",R.drawable.dog2, "张四", 19);
        Student s3 = new Student("18003",R.drawable.dog3, "张五", 20);
        Student s4 = new Student("18004",R.drawable.dog4, "张六", 17);
        Student s5 = new Student("18005",R.drawable.dog5, "张七", 21);
        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
        studentArrayList.add(s4);
        studentArrayList.add(s5);
    }


    @Override
    /*删除学生*/
    public void del(final int i) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage("你确定要删除吗？");
        //点击对话框以外的区域是否让对话框消失
        builder.setCancelable(true);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                studentArrayList.remove(i);
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        builder.show();
    }
}
